<template>
  <div>
    <el-card shadow="never">
      <template slot="header">
        <span>客户订单列表</span>
      </template>

      <!-- 搜索区域 -->
      <Search :search-options="searchOptions" @search="handleSearch" />

      <!-- 订单表格 -->
      <el-table v-loading="listLoading" element-loading-text="数据正在加载中" :data="data" border fit
                highlight-current-row style="width: 100%" @sort-change="handleSortChange">
        <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
                         :align="item.align" :width="item.width">
          <template slot-scope="{ row, $index }">
            <!-- 序号 -->
            <div v-if="item.prop === 'index'">
              {{ $index + 1 }}
            </div>
            <div v-else-if="item.prop === 'materialType'">
              {{ MATERIAL_TYPE_MAP[row.materialType]?.label || row.materialType }}
            </div>
            <!-- 订单类型 -->
            <div v-else-if="item.prop === 'orderType'">
              <el-tag :type="ORDER_TYPE_MAP[row.orderType]?.type || 'info'">
                {{ ORDER_TYPE_MAP[row.orderType]?.label || row.orderType }}
              </el-tag>
            </div>
            <!-- 订单状态 -->
            <div v-else-if="item.prop === 'orderStatus'">
              <el-tag :type="ORDER_STATUS_MAP[row.orderStatus]?.type || 'info'">
                {{ ORDER_STATUS_MAP[row.orderStatus]?.label || row.orderStatus }}
              </el-tag>
            </div>
            <!-- 价格相关字段 -->
            <div
              v-else-if="['orderPrice', 'manageFee', 'retainerAmount', 'stopProfitLimit', 'stopLossLimit'].includes(item.prop)">
              <span class="price-text">¥{{ formatPrice(row[item.prop]) }}</span>
            </div>
            <!-- 重量字段 -->
            <div v-else-if="item.prop === 'weight'">
              <span>{{ formatWeight(row.weight) }}g</span>
            </div>
            <!-- 时间字段 -->
            <div v-else-if="item.prop === 'orderTime'">
              <span>{{ formatDateTime(row.orderTime) }}</span>
            </div>
            <!-- 默认显示 -->
            <div v-else>
              {{ row[item.prop] || '-' }}
            </div>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="handleView(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination :page="current" :page_size="size" :total="total" @sizeChange="sizeChange"
                  @currentChange="pageChange" />
    </el-card>
  </div>
</template>

<script>
import Search from '@/components/Search.vue'
import Pagination from '@/components/Pagination.vue'
import { SEARCH_OPTIONS, columns, ORDER_STATUS_MAP, ORDER_TYPE_MAP, MATERIAL_TYPE_MAP } from '@/views/order/options'
import { getOrderList } from '@/views/order/api/order'

export default {
  name: 'CustomerOrderList',
  components: {
    Search,
    Pagination
  },
  props: {
    customerId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 搜索和表格配置
      searchOptions: [
        {
          label: '订单编号',
          key: 'orderNo',
          type: 'input',
          placeholder: '请输入订单编号',
          value: null,
        },
        {
          label: '订单类型',
          key: 'orderType',
          type: 'select',
          options: [
            { label: '买料', value: 'BUY' },
            { label: '卖料', value: 'SELL' }
          ],
          value: null,
        },
        {
          label: '订单状态',
          key: 'orderStatus',
          type: 'select',
          options: [
            { label: '已定价', value: 'PENDING' },
            { label: '已违约结算', value: 'CANCELLED' },
            { label: '已结算', value: 'COMPLETED' }
          ],
          value: null,
        },
        {
          label: '下单时间',
          key: 'orderTime',
          type: 'daterange',
          startKey: 'startTime',
          endKey: 'endTime',
          value: [],
        },
        {
          label: '物料类型',
          key: 'materialType',
          type: 'select',
          options: [
            { label: '黄金', value: 'GOLD' }
          ],
          value: null,
        }],
      MATERIAL_TYPE_MAP,
      columns: columns,
      ORDER_STATUS_MAP,
      ORDER_TYPE_MAP,

      // 数据相关
      listLoading: false,
      data: [],
      current: 1,
      total: 0,
      size: 20,
      searchParams: {}
    }
  },
  watch: {
    customerId: {
      handler(newVal) {
        if (newVal) {
          this.current = 1;
          this.init();
        }
      },
      immediate: true
    }
  },
  methods: {
    // 初始化
    init() {
      // 只有当customerId存在时才获取数据
      if (!this.customerId) {
        this.data = [];
        this.total = 0;
        return;
      }
      
      this.getList()
    },

    // 获取订单列表
    async getList() {
      // 只有当customerId存在时才获取数据
      if (!this.customerId) {
        this.data = [];
        this.total = 0;
        return;
      }
      
      this.listLoading = true
      try {
        const params = {
          current: this.current,
          size: this.size,
          ...this.searchParams,
          cusId: this.customerId  // 添加客户ID参数
        }

        const res = await getOrderList(params)

        this.total = res.total || res.count || 0
        this.data = res.records || res.list || []
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 搜索处理
    handleSearch(params) {
      this.searchParams = { ...params }
      this.current = 1
      this.getList()
    },

    // 排序处理
    handleSortChange(sort) {
      if (sort.prop && sort.order) {
        this.searchParams.sortBy = sort.prop
        this.searchParams.sortOrder = sort.order === 'ascending' ? 'asc' : 'desc'
        this.getList()
      }
    },

    // 分页变化
    pageChange(page) {
      this.current = page
      this.getList()
    },

    sizeChange(size) {
      this.size = size
      this.current = 1
      this.getList()
    },

    // 查看订单
    handleView(row) {
      if (!row || !row.id) {
        this.$message.warning('无法获取订单ID')
        return
      }
      this.$router.push(`/order/detail/${row.id}`)
    },

    // 格式化价格（千分位，保留两位小数）
    formatPrice(price) {
      if (price === null || price === undefined) return '0.00'
      const num = Number(price)
      if (!isFinite(num)) return '0.00'
      return num.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return dateTime;
    },

    // 重量 千分符
    formatWeight(weight) {
      if (weight === null || weight === undefined || weight === '') return '0'
      const num = Number(weight)
      if (!isFinite(num)) return '0'
      return num.toLocaleString('zh-CN')
    },

    // 提供给父组件调用的搜索方法
    handleSearchFromParent() {
      this.current = 1;
      this.getList();
    }
  }
}
</script>

<style lang="scss" scoped>
.price-text {
  color: #e6a23c;
  font-weight: 500;
}

.el-tag {
  margin-right: 5px;
}

.search-container {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>